package com.lagou.edu.service.impl;

import com.lagou.edu.common.CodeMessage;
import com.lagou.edu.dao.CodeDao;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.pojo.Result;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.utils.LagouUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.Calendar;
import java.util.Date;

/**
 * @Author 梅松
 * @Date 2021/10/19 16:45
 */
@Service
public class CodeServiceImpl implements CodeService {
    @Autowired
    private CodeDao codeDao;
    @Value("${code.expire-time}")
    private int expireTime;

    /**
     * 判断email是否已经存在
     * @param email
     * @return
     */
    @Override
    public Boolean isEmailExist(String email){
        LagouAuthCode lagouAuthCode = codeDao.findLagouAuthCodeByEmail(email);
        return lagouAuthCode!=null?true:false;
    }

    /**
     * 判断验证码是否过期
     * 过期时间是否早于现在的时间
     * @param code
     * @return
     */
    @Override
    public Boolean isExipired(LagouAuthCode code){
       return code.getExpiretime().before(new Date());
    }

    @Override
    @Transactional
    public Long saveCode(String code,String email){
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCode(code);
        lagouAuthCode.setEmail(email);
        Date createTime = new Date();
        lagouAuthCode.setCreatetime(createTime);
        Calendar c = Calendar.getInstance();
        c.setTime(createTime);
        c.add(Calendar.SECOND,expireTime);
        lagouAuthCode.setExpiretime(c.getTime());
        lagouAuthCode = codeDao.save(lagouAuthCode);
        return lagouAuthCode.getId();
    }

    /**
     * 根据email查询code
     * @param email
     * @return
     */
    @Override
    public LagouAuthCode findCodeByEmail(String email){
        return codeDao.findLagouAuthCodeByEmail(email);
    }

    @Override
    public Result<Boolean> checkCode(String email, String code){
        //1、根据邮箱查询验证码，如果查询不到，返回请获取验证码
        LagouAuthCode lagouAuthCode = codeDao.findLagouAuthCodeByEmail(email);
        if(lagouAuthCode == null){
            return Result.fail("没有生成验证码");
        }
        //2、判断验证码是否过期，如果过期，返回验证码过期信息
        if(lagouAuthCode.isExpired()){
            return Result.fail("注册码已过期，请重新获取");
        }
        //3、判断验证码是否正确，如果验证码错误，返回验证码错误信息
        if(!lagouAuthCode.getCode().equals(code)){
            return Result.fail("验证码错误");
        }
         //4、返回验证成功信息
        return Result.ok("验证码成功");
    }

    @Override
    @Transactional
    public Result deleteCode(String email){
        codeDao.deleteLagouAuthCodeByEmail(email);
        return Result.ok("删除成功");
    }
}
